package com.gitee.feizns.explore.data_structure.stack.brackets;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author feizns
 * @since 2019/10/12
 */
public class Brackets {

    public static void main(String[] args) {
        System.out.println(isValid("(())"));
    }

    private static Map<Character, Character> MAP = new HashMap<Character, Character>(){
        {
            put('(', ')');
            put('[', ']');
            put('{', '}');
        }
    };

    public static boolean isValid(String s) {
         if ( s == null || s.length() % 2 != 0 )
             return false;

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ( MAP.containsKey(c) )
                stack.push(c);
            else if ( stack.isEmpty() || !(MAP.get(stack.pop()).equals(c)) )
                return false;
        }

        return stack.isEmpty();
    }

}
